﻿using UnityEngine;
using UnityEditor;
using System;

namespace xshare
{


    public class xBehaviour : MonoBehaviour
    {

        static xBehaviour s_inst;

        public static void Initialize()
        {
            if (null != s_inst) //#先调用了Awake, 再调用这个函数:
            {
                Debug.Log($"xBehaviour has init");
                return;
            }

            var inst = FindObjectOfType<xBehaviour>();
            if (null == inst) //#先调用了该函数, 再调用Awake(下个场景挂了xBehaviour): 第2个xRes不起任何作用
            {
                inst = new GameObject("xBehaviour").AddComponent<xBehaviour>(); //Awake被调用
            }
            else //#先调用了该函数, 再调用Awake(调用Initialize的Awake函数优先级更高):
            {
                inst.Init();
            }
        }

        //========== Update

        public static event Action<float> OnUpdate
        {
            add
            {
                s_inst.onUpdate += value;
            }

            remove
            {
                s_inst.onUpdate -= value;
            }
        }

        //==========

        Action<float> onUpdate;

        void Awake()
        {
            Debug.Log($"xBehaviour: Awake");
            if (null != s_inst)
            {
                Debug.Log($"xBehaviour: only first instance valid");
                return;
            }

            Init();
        }

        void Init()
        {
            if (null != s_inst)
                return;

            s_inst = this;
            DontDestroyOnLoad(gameObject);

            MainThreadSync.Initialize();
        }

        void Update()
        {
            MainThreadSync.OnUpdate();

            if (null != onUpdate)
            {
                try
                {
                    onUpdate.Invoke(Time.deltaTime);
                }
                catch (Exception ex)
                {
                    Debug.Log($"exception: {ex.GetType().Name}: {ex.Message}");
                    Debug.LogError(ex.StackTrace);
                }
            }
        }

    } //end of class


}
